[[...path]].page.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import React, { useEffect } from 'react';
  2. import { isClient } from '@growi/core';
  3. import type { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  4. import type {
  5. GetServerSideProps, GetServerSidePropsContext,
  6. } from 'next';
  7. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  11. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  12. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  13. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  14. import { ShareLinkPageView } from '~/components/ShareLink/ShareLinkPageView';
  15. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  16. import type { CrowiRequest } from '~/interfaces/crowi-request';
  17. import type { RendererConfig } from '~/interfaces/services/renderer';
  18. import type { IShareLinkHasId } from '~/interfaces/share-link';
  19. import type { PageDocument } from '~/server/models/page';
  20. import {
  21. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  22. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid,
  23. } from '~/stores/context';
  24. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  25. import loggerFactory from '~/utils/logger';
  26. import type { NextPageWithLayout } from '../_app.page';
  27. import {
  28. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, CommonProps,
  29. } from '../utils/commons';
  30. const logger = loggerFactory('growi:next-page:share');
  31. type Props = CommonProps & {
  32. shareLinkRelatedPage?: IShareLinkRelatedPage,
  33. shareLink?: IShareLinkHasId,
  34. isNotFound: boolean,
  35. isExpired: boolean,
  36. disableLinkSharing: boolean,
  37. isSearchServiceConfigured: boolean,
  38. isSearchServiceReachable: boolean,
  39. isSearchScopeChildrenAsDefault: boolean,
  40. drawioUri: string | null,
  41. rendererConfig: RendererConfig,
  42. skipSSR: boolean,
  43. };
  44. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  45. superjson.registerCustom<IShareLinkRelatedPage, string>(
  46. {
  47. isApplicable: (v): v is IShareLinkRelatedPage => {
  48. return v != null
  49. && v.toObject != null
  50. && v.lastUpdateUser != null
  51. && v.creator != null
  52. && v.revision != null;
  53. },
  54. serialize: (v) => { return superjson.stringify(v.toObject()) },
  55. deserialize: (v) => { return superjson.parse(v) },
  56. },
  57. 'IShareLinkRelatedPageTransformer',
  58. );
  59. // GrowiContextualSubNavigation for shared page
  60. // get page info from props not to send request 'GET /page' from client
  61. type GrowiContextualSubNavigationForSharedPageProps = {
  62. page?: IPagePopulatedToShowRevision,
  63. isLinkSharingDisabled: boolean,
  64. }
  65. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  66. const { page, isLinkSharingDisabled } = props;
  67. return (
  68. <div data-testid="grw-contextual-sub-nav">
  69. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled}/>
  70. </div>
  71. );
  72. };
  73. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  74. useCurrentPathname(props.shareLink?.relatedPage.path);
  75. useIsSearchPage(false);
  76. useIsNotFound(props.isNotFound);
  77. useShareLinkId(props.shareLink?._id);
  78. useCurrentPageId(props.shareLink?.relatedPage._id);
  79. useCurrentUser(props.currentUser);
  80. useRendererConfig(props.rendererConfig);
  81. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  82. useIsSearchServiceReachable(props.isSearchServiceReachable);
  83. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  84. useIsContainerFluid(props.isContainerFluid);
  85. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  86. useEffect(() => {
  87. if (!props.skipSSR) {
  88. return;
  89. }
  90. if (props.shareLink?.relatedPage._id != null && !props.isNotFound && props.skipSSR) {
  91. mutateCurrentPage();
  92. }
  93. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  94. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(props.shareLinkRelatedPage);
  95. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  96. const title = generateCustomTitleForPage(props, pagePath);
  97. return (
  98. <>
  99. <Head>
  100. <title>{title}</title>
  101. </Head>
  102. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  103. <header className="py-0 position-relative">
  104. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  105. </header>
  106. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  107. <ShareLinkPageView
  108. pagePath={pagePath}
  109. rendererConfig={props.rendererConfig}
  110. page={currentPage ?? props.shareLinkRelatedPage}
  111. shareLink={props.shareLink}
  112. isExpired={props.isExpired}
  113. disableLinkSharing={props.disableLinkSharing}
  114. />
  115. </div>
  116. </>
  117. );
  118. };
  119. SharedPage.getLayout = function getLayout(page) {
  120. return (
  121. <>
  122. <DrawioViewerScript />
  123. <ShareLinkLayout>{page}</ShareLinkLayout>
  124. </>
  125. );
  126. };
  127. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  128. const req: CrowiRequest = context.req as CrowiRequest;
  129. const { crowi } = req;
  130. const { configManager, searchService } = crowi;
  131. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  132. props.isSearchServiceConfigured = searchService.isConfigured;
  133. props.isSearchServiceReachable = searchService.isReachable;
  134. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  135. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  136. props.rendererConfig = {
  137. isSharedPage: true,
  138. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  139. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  140. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  141. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  142. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  143. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  144. // XSS Options
  145. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  146. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  147. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  148. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  149. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  150. };
  151. }
  152. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  153. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  154. props._nextI18Next = nextI18NextConfig._nextI18Next;
  155. }
  156. function getAction(props: Props): SupportedActionType {
  157. let action: SupportedActionType;
  158. if (props.isExpired) {
  159. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  160. }
  161. else if (props.shareLink == null) {
  162. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  163. }
  164. else {
  165. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  166. }
  167. return action;
  168. }
  169. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  170. const req: CrowiRequest = context.req as CrowiRequest;
  171. const parameters = {
  172. ip: req.ip,
  173. endpoint: req.originalUrl,
  174. action,
  175. user: req.user?._id,
  176. snapshot: {
  177. username: req.user?.username,
  178. },
  179. };
  180. await req.crowi.activityService.createActivity(parameters);
  181. }
  182. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  183. const req = context.req as CrowiRequest<IUserHasId & any>;
  184. const { crowi, params } = req;
  185. const result = await getServerSideCommonProps(context);
  186. if (!('props' in result)) {
  187. throw new Error('invalid getSSP result');
  188. }
  189. const props: Props = result.props as Props;
  190. const skipSSR = (shareLinkRelatedPage: IShareLinkRelatedPage) => {
  191. if (shareLinkRelatedPage.latestRevisionBodyLength == null) {
  192. return true;
  193. }
  194. const ssrMaxRevisionBodyLength = crowi.configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  195. if (ssrMaxRevisionBodyLength < shareLinkRelatedPage.latestRevisionBodyLength) {
  196. return true;
  197. }
  198. return false;
  199. };
  200. try {
  201. const ShareLinkModel = crowi.model('ShareLink');
  202. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  203. if (shareLink == null) {
  204. props.isNotFound = true;
  205. }
  206. else {
  207. props.isNotFound = false;
  208. props.skipSSR = skipSSR(shareLink.relatedPage);
  209. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  210. props.isExpired = shareLink.isExpired();
  211. props.shareLink = shareLink.toObject();
  212. }
  213. }
  214. catch (err) {
  215. logger.error(err);
  216. }
  217. injectServerConfigurations(context, props);
  218. await injectNextI18NextConfigurations(context, props);
  219. await addActivity(context, getAction(props));
  220. return {
  221. props,
  222. };
  223. };
  224. export default SharedPage;